package cn.tedu.egweibo5.controller;

import cn.tedu.egweibo5.base.response.JsonResult;
import cn.tedu.egweibo5.base.response.StatusCode;
import cn.tedu.egweibo5.mapper.UserMapper;
import cn.tedu.egweibo5.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo5.pojo.dto.UserRegDTO;
import cn.tedu.egweibo5.pojo.entity.User;
import cn.tedu.egweibo5.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author Justin Parker
 * @author 2024/8/14 22:20
 * @version 1.0
 */
@Slf4j
@Api(tags = "用户模块")
@Validated
@RestController
@RequestMapping("/v1/users")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "注册功能")
    @PostMapping("/reg")
    public JsonResult reg(@RequestBody @Validated UserRegDTO userRegDTO){

        String username = userRegDTO.getUsername();

        UserVO userVO = userMapper.selectByUsername(username);
        if (userVO != null){
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return JsonResult.ok();
    }

    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody  UserLoginDTO userLoginDTO,@ApiIgnore HttpSession session){
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        UserVO userVO = userMapper.selectByUsername(username);
        if (userVO == null){
            return new  JsonResult(StatusCode.USERNAME_ERROR);
        }
        if (userVO.getPassword().equals(password)){
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.PASSWORD_ERROR);
    }

    @ApiOperation(value = "获取当前用户功能")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        UserVO userVO =(UserVO) session.getAttribute("user");
        return JsonResult.ok(userVO);
    }

    @ApiOperation(value = "退出功能")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");

    }
}
